<template>
  <div id="addContent" class="main-box">
    <BaseTitle :title="$t('栏目内容管理')">
      <template #right>
        <BackBtn :back-funtion="prev" />
      </template>
    </BaseTitle>
    <el-form ref="form" :model="addForm" :rules="rules" class="flexForm" label-position="top">
      <div class="left">
        <el-form ref="searchForm" :model="searchForm" :rules="searchRules" label-width="top" class="filter-form">
          <el-form-item :label="$t('站点')" prop="site_id">
            <el-select v-model="searchForm.site_id" multiple @change="webChange">
              <el-option v-for="item in webList" :key="item.id" :label="item.domain" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('主栏目')" prop="category_id">
            <el-select v-model="searchForm.category_id" @change="handleChangeColumn" filterable>
              <el-option-group v-for="group in columnList" :key="group.id" :label="group.title">
                <el-option v-for="item in group.category" :key="item.id"
                  :label="item.parent_id != 0 ? `${item.title}` : item.title" :value="item.id"
                  :disabled="item.disabled" />
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('副栏目')">
            <el-select v-model="searchForm.subColumnId" filterable multiple>
              <el-option-group v-for="group in subColumnList" :key="group.id" :label="group.title">
                <el-option v-for="item in group.category" :key="item.id" :label="item.title" :value="item.id"
                  :disabled="item.disabled" />
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-upload2" @click="batchUpload">
              {{ $t('批量上传') }}
            </el-button>
          </el-form-item>
        </el-form>
        <SubTitle :title="$t('基本信息')" />
        <el-form-item prop="sub_content.title" :label="`${$t('标题')}:`">
          <el-input v-model="addForm.sub_content.title" :placeholder="$t('请输入标题')" />
        </el-form-item>
        <el-form-item prop="sub_content.sub_title" :label="`${$t('副标题')}:`">
          <el-input v-model="addForm.sub_content.sub_title" :placeholder="$t('请输入副标题')" />
        </el-form-item>
        <el-form-item prop="sub_content.description" :label="`${$t('简介')}:`">
          <el-input v-model="addForm.sub_content.description" :placeholder="$t('请输入简介')" type="textarea"
            :autosize="{ minRows: 4 }" />
        </el-form-item>
        <el-form-item :label="`${$t('内容')}:`">
          <div>
            <MyTinymce ref="myTinymce" :tinymce-html="content" @changeDescription="changeDescription" />
          </div>
        </el-form-item>
        <el-form-item :label="`${$t('标签')}:`">
          <el-input v-model="addForm.sub_content.tag" :placeholder="$t('标签之间用逗号隔开')" />
        </el-form-item>
      </div>
      <div class="right">
        <SubTitle :title="$t('SEO设置')" />
        <el-form-item prop="seo_title" label="Title:">
          <el-input v-model="addForm.sub_content.seo_title" :placeholder="$t('请输入seo标题')" />
        </el-form-item>
        <el-form-item prop="seo_keyword" label="Keyword:">
          <el-input v-model="addForm.sub_content.seo_keyword" :placeholder="$t('请输入seo关键词')" />
        </el-form-item>
        <el-form-item prop="seo_description" label="Description:">
          <el-input v-model="addForm.sub_content.seo_description" type="textarea" :placeholder="$t('请输入seo描述')"
            :autosize="{ minRows: 4 }" />
        </el-form-item>
        <SubTitle :title="$t('其他信息')" />
        <el-form-item prop="author" :label="`${$t('作者')}:`">
          <el-input v-model="addForm.sub_content.author" :placeholder="$t('请输入作者名称')" />
        </el-form-item>
        <el-form-item :label="`${$t('模板')}:`">
          <el-select v-model="addForm.sub_content.detail_tpl">
            <el-option v-for="item in themeList" :key="item.id" :label="item.file" :value="item.file" />
          </el-select>
        </el-form-item>
        <el-form-item prop="url" :label="`${$t('跳转链接')}:`">
          <el-input v-model="addForm.sub_content.url" :placeholder="$t('请输入跳转链接')" />
        </el-form-item>
        <el-form-item :label="`${$t('发布时间')}:`" prop="publish_time">
          <el-date-picker v-model="addForm.sub_content.publish_time" type="datetime" :placeholder="$t('请选择发布时间')"
            value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item prop="hits" :label="`${$t('浏览量')}:`">
          <el-input v-model="addForm.sub_content.hits" :placeholder="$t('请输入浏览量')" />
        </el-form-item>
        <el-form-item prop="sort" :label="`${$t('排序')}:`">
          <el-input v-model="addForm.sub_content.sort" :placeholder="$t('请输入排序')" />
        </el-form-item>
        <el-form-item prop="status" :label="`${$t('状态')}:`">
          <el-switch v-model="addForm.sub_content.status" :active-text="$t('正常')" :inactive-text="$t('禁用')"
            active-value="1" inactive-value="2" active-color="var(--huocms-com-color-primary)"
            inactive-color="rgba(0,0,0,0.2)" />
        </el-form-item>
        <el-form-item prop="is_top" :label="`${$t('是否置顶')}:`">
          <el-switch v-model="addForm.sub_content.is_top" :active-text="$t('置顶')" :inactive-text="$t('否')"
            active-value="1" inactive-value="2" active-color="var(--huocms-com-color-primary)"
            inactive-color="rgba(0,0,0,0.2)" />
        </el-form-item>
        <el-form-item prop="is_recommend" :label="`${$t('是否推荐')}:`">
          <el-switch v-model="addForm.sub_content.is_recommend" :active-text="$t('推荐')" :inactive-text="$t('否')"
            active-value="1" inactive-value="2" active-color="var(--huocms-com-color-primary)"
            inactive-color="rgba(0,0,0,0.2)" />
        </el-form-item>

        <el-form-item size="small" :label="`${$t('缩略图')}:`">
          <div class="attachment_imgBox" @click="openList('thumbnail')">
            <img v-if="addForm.sub_content.thumbnail" :src="thumbnailImg" class="attachmentImg" />
            <i v-else class="el-icon-camera" />
            <span v-if="addForm.sub_content.thumbnail" class="img-actions attachmentImg">
              <span @click.stop="handleRemove(1)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
          <Attachment ref="attachment" :dialog-show.sync="dialogShow" :attachment-type="attachmentType" @func="getData" />
        </el-form-item>
        <el-form-item :label="`${$t('详情页banner')}:`">
          <div class="attachment_imgBox" @click="openList('cover')">
            <img v-if="addForm.sub_content.cover" :src="coverImg" class="attachmentImg" />
            <i v-else class="el-icon-camera" />
            <span v-if="addForm.sub_content.cover" class="img-actions attachmentImg">
              <span @click.stop="handleRemove(2)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <div style="width: 100%">
      <SubTitle :title="$t('附加信息')" />
      <PublicForm ref="PublicForm" :form-obj="formObj" :form-data="formData" :rules="mainRules" />
    </div>
    <br />
    <div class="flexCenter">
      <el-button type="primary" @click="onSubmit(3)" class="tianBlue">
        {{ $t('暂存') }}
      </el-button>
      <el-button :loading="loading" type="primary" @click="onSubmit()">
        {{ $t('提交') }}
      </el-button>
    </div>
    <BaseDialog :title="$t('批量上传')" :dialog-show.sync="dialogShow2" @submit="dialogShow2 = false" width="50%" footer>
      <el-form label-position="top">
        <el-form-item :label="`${$t('文件')}:`">
          <el-upload ref="upload" :headers="myHeaders" :action="$store.getters.updateURL + 'content/articleUpload'"
            class="bulkImort" :data="bulkData" :show-file-list="true" :on-success="bulkImportSuccess"
            :before-upload="beforeBulkImport" :on-change="bulkChange" :multiple="true">
            <el-button size="small" type="primary" icon="el-icon-upload2">
              {{ $t('批量上传') }}
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="pseudo" @change="changePseudo">
            {{ $t('伪原创') }}
          </el-checkbox>
        </el-form-item>
      </el-form>
    </BaseDialog>
  </div>
</template>

<script>
import columnApi from '@/api/column'
import moduleApi from '@/api/module'
import tempApi from '@/api/theme'
import PublicForm from './components/form.vue'
import tagApi from '@/api/tag.js'
import webApi from '@/api/website'
import { mapGetters } from 'vuex'

export default {
  name: 'AddArticle',
  components: { PublicForm },

  data() {
    return {
      pseudo: false,
      themeList: [],
      dialogShow2: false,
      myHeaders: { Authorization: `Bearer ${this.$store.getters.token}` },
      bulkData: {},
      attachmentLimit: 10,
      webList: [],
      type: '',
      dialogShow: false,
      thumbnailImg: '',
      coverImg: '',
      attachmentData: [],
      content: '',
      html: '',
      formObj: [],
      formData: {},
      mainRules: [],
      searchForm: {
        model_id: '',
        category_id: [],
        site_id: []
      },
      searchRules: {
        site_id: [
          { required: true, message: this.$t('请选择站点'), trigger: 'change' }
        ],
        category_id: [
          { required: true, message: this.$t('请选择栏目'), trigger: 'change' }
        ]
      },
      moduleList: [],
      columnList: [],
      subColumnList: [], // 副栏目数据
      currentModuleId: '', // 当前选择模型id
      formTypeSource: {}, // 自定义字段数据源
      website_id: '',
      headers: {},
      imageUrl: '',
      imgUrl: this.$store.getters.updateURL,
      checkList: [],
      tindata: '',
      ticShow: false,
      options: [],
      value: '',
      pageLoading: false, // 页面加载
      id: '',
      loading: false,
      form: {
        label: '',
        title: '',
        cate_id: '',
        push_time: '',
        image_url: '',
        content: '',
        source: '词爪官方',
        is_hot: 2
        // content1: '', // 富文本原文
        // content2: '' // 富文本html
      },
      rules: {
        sub_content: {
          title: [
            {
              required: true,
              message: this.$t('请选择文章标题'),
              trigger: 'blur'
            }
          ]
        },
        main_content: {
          title: [
            {
              required: true,
              message: this.$t('请选择文章标题'),
              trigger: 'blur'
            }
          ]
        }
      },
      addForm: {
        website_id: '',
        category_id: '',
        // 主表固定字段
        sub_content: {
          title: '',
          sub_title: '',
          detail_tpl: '',
          description: '',
          thumbnail: '',
          cover: '',
          hits: '',
          author: '',
          status: '1',
          url: '',
          is_top: '',
          is_recommend: '',
          sort: '',
          seo_title: '',
          seo_keyword: '',
          seo_description: ''
        },
        // 副表字段
        main_content: {
          title: ''
        }
      },
      tagData: [],
      attachmentType: ''
    }
  },
  computed: {
    ...mapGetters(['siteId'])
  },
  watch: {
    siteId(val, value) {
      if (value) {
        this.$router.push({ name: 'Content' })
      }
    }
  },
  created() {
    const str = 'content'
    const res = () => import('./' + str + '.vue')
    this.lang = this.$route.query.lang
    this.bulkData = {
      module_id: this.$route.query.module_id,
      category_id: this.$route.query.category_id,
      pseudo: this.pseudo ? '1' : '2'
    }
    this.getWebList()
    if (this.siteId) {
      this.getList()
    }
    this.getTemp()
  },
  updated() {
    this.bulkData.pseudo = this.pseudo ? '1' : '2'
  },
  methods: {
    // 移除图片数据
    handleRemove(type) {
      if (type == 1) {
        // 移除缩略图
        this.addForm.sub_content.thumbnail = ''
        this.thumbnailImg = ''
      } else {
        // 移除banner图
        this.addForm.sub_content.cover = ''
        this.coverImg = ''
      }
    },
    handleChangeColumn(e) {
      this.getSubColumnList(e)
      this.searchForm.subColumnId = []
    },
    changePseudo() { },
    // 获取主栏目列表
    async getColumnList() {
      if (this.searchForm.site_id.length) {
        const res = await moduleApi.getModuleCate({
          lang: this.lang,
          site_id: this.searchForm.site_id
        })
        this.columnList = res.data
      } else {
        this.columnList = []
      }
    },
    // 更改主栏目
    getSubColumnList(e) {
      this.searchForm.subColumnId = []
      const newData = []
      this.columnList.find(item => {
        const result = item.category.find(child => child.id == e)
        if (result?.module_id) {
          this.currentModuleId = result.module_id
        }
      })
      this.columnList.forEach(item => {
        newData.push({
          ...item,
          category: item.category.filter(
            item => item.module_id === this.currentModuleId && item.id !== e
          )
        })
      })
      this.subColumnList = newData
      this.getSubform()
    },
    // 获取主副表的字段
    getSubform() {
      this.addForm.module_id = this.currentModuleId
      this.addForm.category_id = this.searchForm.category_id
      this.addForm.website_id = this.website_id
      moduleApi.fieldList({ module_id: this.currentModuleId }).then(res => {
        if (res.code == 0) {
          this.formObj = []
          const arr = Object.values(res.data)
          arr.forEach(el => {
            if (el.form_type == 'checkbox') {
              this.$set(this.formData, el.table_field, [])
            } else {
              this.$set(this.formData, el.table_field, '')
            }
            let arr2 = []
            var option = []
            if (el.validate_rule == 'require') {
              el.validate_rule = [
                {
                  required: true,
                  message: this.$t('此内容为必填内容'),
                  trigger: 'blur'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule,
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule,
                  list: [],
                  id: el.id
                })
              }
            } else if (
              el.validate_rule == 'date' ||
              el.validate_rule == 'time'
            ) {
              el.validate_rule = [
                {
                  required: true,
                  message: this.$t('请选择日期或时间'),
                  trigger: 'blur'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule,
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule,
                  list: [],
                  id: el.id
                })
              }
            } else if (el.validate_rule == 'email') {
              el.validate_rule = [
                {
                  required: true,
                  message: this.$t('请输入邮箱'),
                  trigger: 'blur'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule,
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule,
                  list: [],
                  id: el.id
                })
              }
            } else if (el.form_type == 'reference') {
              if (
                el.settings.relation == 'has_one' ||
                el.settings.relation == 'belongs_to'
              ) {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == '' ? [] : el.validate_rule,
                  options: el.attach_data,
                  list: [],
                  id: el.id,
                  multiple: false, // 单选
                  relation_file: el.settings.foreign_key
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == '' ? [] : el.validate_rule,
                  options: el.attach_data,
                  list: [],
                  id: el.id,
                  multiple: true, // 多选
                  relation_file: el.settings.foreign_key
                })
              }
            } else {
              el.validate_rule = []
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule,
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule,
                  list: [],
                  id: el.id
                })
              }
            }
          })
        }
      })
    },

    getData(data) {
      if (data.length > 1) {
        this.$message.error(this.$t(this.$t('最多只能选择一张图片')))
      } else {
        if (this.type == 'thumbnail') {
          this.addForm.sub_content.thumbnail = data[0].id
          this.thumbnailImg = data[0].url
        } else if (this.type == 'cover') {
          this.addForm.sub_content.cover = data[0].id
          this.coverImg = data[0].url
        }
        this.dialogShow = false
      }
    },
    // 打开附件弹窗
    openList(val) {
      this.dialogShow = true
      this.attachmentType = 2
      this.$nextTick(() => {
        this.$refs.attachment.getAttachmentList()
        this.$refs.attachment.$refs.AttachmentCate.getCateList(0)
      })
      this.type = val
    },
    getTemp() {
      tempApi
        .webTempList({ website_id: this.siteId, lang: this.lang })
        .then(res => {
          this.themeList = res.data
        })
    },
    batchUpload() {
      if (this.searchForm.site_id.length == 0) {
        this.$message.error(this.$t('站点不能为空'))
        return false
      }
      if (this.searchForm.site_id.length > 1) {
        this.$message.error(this.$t('只能选择一个站点下的栏目上传内容'))
        return false
      }
      this.bulkData.category_id = this.searchForm.category_id
      this.bulkData.website_id = this.searchForm.site_id[0]

      this.dialogShow2 = true
      // 打开弹窗 清空上传列表
      this.$nextTick(el => {
        this.$refs.upload.clearFiles()
      })
    },
    // 提取的简介
    changeDescription(description) {
      this.addForm.sub_content.description = description
    },
    beforeBulkImport(file) {
      const isTXT = file.type === 'text/plain'
      if (!isTXT) {
        this.$message.error(this.$t('批量上传仅支持txt'))
      }
      return isTXT
    },
    bulkChange(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    // 批量导入
    bulkImportSuccess(res, file) {
      if (res.code == 0) {
        this.$message.success(res.msg)
      }
    },
    // 标签列表
    getList() {
      const val = {
        limit: 100,
        page: 1,
        website_id: this.siteId,
        lang: this.lang
      }
      tagApi.tagList(val).then(res => {
        this.tagData = res.data
      })
    },
    // 站点列表
    async getWebList() {
      const res = await webApi.websiteList()
      this.getTreeData(res.data)
    },
    // 递归获取到站点的数据
    getTreeData(data) {
      const webListArray = []
      function transformWebList(data) {
        if (data.length) {
          data.forEach(item => {
            webListArray.push({
              id: item.id,
              domain: item.parent_id != 0 ? `--${item.domain}` : item.domain,
              parent_id: item.parent_id
            })
            if (item.children.length) {
              transformWebList(item.children)
            }
          })
        }
      }
      transformWebList(data)
      this.webList = webListArray
      this.$nextTick(() => {
        if (this.siteId) {
          this.searchForm.site_id = [+this.siteId]
        }
        this.getColumnList()
      })
    },
    webChange(val) {
      this.searchForm.site_id = val
      this.searchForm.category_id = []
      this.searchForm.subColumnId = []
      this.getColumnList()
    },
    // 提交按钮
    onSubmit(status = 1) {
      this.addForm.sub_content = {
        ...this.addForm.sub_content,
        content: this.getTin(),
        category_id: this.searchForm.category_id,
        sub_category_ids: this.searchForm.subColumnId.join(','),
        status
      }
      // 判断副表有无富文本
      const newArr = this.$refs.PublicForm.$refs.myTinymce
      if (newArr) {
        newArr.forEach(item => {
          this.formData[item.prop] = item.codeValue
        })
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          const obj = {
            module_id: this.currentModuleId,
            category_id: [
              this.searchForm.category_id,
              ...this.searchForm.subColumnId
            ],
            lang: this.lang,
            main_content: this.formData,
            sub_content: this.addForm.sub_content
          }
          // return
          this.loading = true
          columnApi.contentSave(obj).then(res => {
            if (res.code == 0) {
              this.$message.success(res.msg)
              this.prev()
            }
            this.loading = false
          })
          this.loading = false
          // }
        } else {
          this.$message.warning(this.$t('请填写必要信息'))
        }
        // })
      })
    },
    // 获取富文本框内容
    getTin() {
      var rs = this.$refs.myTinymce.codeValue
      return rs
    },
    // 返回上一页
    prev() {
      this.$router.push({
        name: 'Content',
        query: { category_id: this.searchForm.category_id, lang: this.lang }
      })
    }
  }
}
</script>

<style lang="scss">
#addContent {

  .el-select,
  .el-input,
  .el-textarea,
  .el-date-editor {
    width: 100%;
  }
}

.attachment .el-dialog {
  height: 640px;
}
</style>
<style scoped lang="scss">
.filter-form {
  .el-form-item {
    margin-bottom: 24px;
  }
}

.avatar {
  height: 100px;
}

.flexCenter {
  margin: 0px 0 16px;
}

@media screen and (max-width: 1380px) {
  .form {
    display: block;
  }

  .left {
    width: 100%;
  }

  .right {
    width: 100%;
  }

  .back {
    top: 25px;
  }
}

.attachment_imgBox .img-actions {
  position: absolute;
  background: rgba($color: #000000, $alpha: 0.3);
  top: 1px;
  left: 3px;
  transition: all 0.5s;
  -moz-transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -o-transition: all 0.5s;
  opacity: 0;
}

.attachment_imgBox .img-actions>span {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

.attachment_imgBox .img-actions>span>i {
  color: #f00;
  font-size: 22px;
}

.attachment_imgBox:hover .img-actions {
  opacity: 1;
}
</style>
